package com.ecut.xzh.service.impl;

import com.alibaba.excel.EasyExcel;
import com.ecut.xzh.constant.MessageConstant;
import com.ecut.xzh.dto.RoommatePageDTO;
import com.ecut.xzh.mapper.RoommateMapper;
import com.ecut.xzh.result.PageResult;
import com.ecut.xzh.service.RoommateService;
import com.ecut.xzh.vo.RoommateVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author XZH
 */
@Service
@Slf4j
public class RoommateServiceImpl implements RoommateService {

    @Resource
    private RoommateMapper roommateMapper;

    /**
     * 分页查询所有用户信息
     *
     * @param roommatePageDTO
     * @return
     */
    @Override
    public PageResult pageRoommate(RoommatePageDTO roommatePageDTO) {
        PageHelper.startPage(roommatePageDTO.getPageNum(), roommatePageDTO.getPageSize());
        Page<RoommateVO> page = roommateMapper.pageRoommate(roommatePageDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 导出Excel
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode(MessageConstant.EXCEL_ROOMMATE, "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 查询出所有数据，写入Excel
        EasyExcel.write(response.getOutputStream(), RoommateVO.class).sheet("室友匹配数据")
                .doWrite(roommateMapper.pageRoommate(new RoommatePageDTO()).getResult());

    }

}
